﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace 植物大战僵尸杂交版数据联网.ExtUrls
{
    class HttpHelper
    {
        public static async Task<string> GetJson(string url)
        {
            using (HttpClient http = new HttpClient())
            {
                http.DefaultRequestHeaders.Add("User-Agent",
             "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36");
                using (HttpResponseMessage res = await http.GetAsync(url))
                {
                    return await res.Content.ReadAsStringAsync();
                }
            }

        }

        public static async Task DownLoad(string url,string host)
        {
            using (HttpClient http = new HttpClient())
            {
                http.BaseAddress = new Uri(host);    
                using (HttpResponseMessage res = await http.GetAsync(url))
                {
                    using (FileStream fs=File.Create($"{ExtUrl.BackUpPath}\\{Path.GetFileName(url)}"))
                    {
                        using (Stream s= await res.Content.ReadAsStreamAsync())
                        {
                            await s.CopyToAsync(fs);
                        }
                    }
                }
            }

        }

        /// <summary>
        /// 请求自己写的API
        /// </summary>
        /// <param name="url"></param>
        /// <param name="host"></param>
        /// <returns></returns>
        public static async Task<string> GetJson(string url, string host)
        {
            using (HttpClient http = new HttpClient())
            {
                http.BaseAddress = new Uri(host);
                using (HttpResponseMessage res = await http.GetAsync(url))
                {
                    return await res.Content.ReadAsStringAsync();
                }
            }
        }

        public static async Task<string> PostJson(string url, string host)
        {
            string[] files = Directory.GetFiles(ExtUrl.BackUpPath);
            using (HttpClient http = new HttpClient())
            {
                http.BaseAddress = new Uri(host);

                using (MultipartFormDataContent m = new MultipartFormDataContent())
                {
                    files.ToList().ForEach(x =>
                    {
                        m.Add(new StreamContent(File.OpenRead(x)), "FormFiles", Path.GetFileName(x));
                    });

                    using (HttpResponseMessage res = await http.PostAsync(url, m))
                    {
                        return await res.Content.ReadAsStringAsync();
                    }
                }
            }
        }
    }
}
